//
//  RegisterView.m
//  Kids
//
//  Created by LiTengFei on 14/11/26.
//  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
//

#import "RegisterView.h"
#import "VerificationCodeRequestData.h"
#import "VerificationCodeResponseData.h"
#import "RequestFactory.h"

#import  "SVProgressHUD.h"

@interface RegisterView()<UITextFieldDelegate>

@property (nonatomic,strong) UITextField * phoneTextField;
@property (nonatomic,strong) UITextField * passwordTextField;
@property (nonatomic,strong) UITextField * codeTextField;
@property (nonatomic,strong) UIButton *getCodeBtn;

@property (nonatomic,assign) NSInteger timerCount;
@property (nonatomic,strong) NSString *verifyCode;

@end

@implementation RegisterView
- (instancetype)init
{

    if (self = [super init]) {

        UIImageView* imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_frame"]];

        [self addSubview:imageView];

        self.frame = CGRectMake(21, 140, 278, 188);

        UIImageView* phoneBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gray"]];
        phoneBackground.frame = CGRectMake(15, 15, 248, 40);
        [self addSubview:phoneBackground];

        UIImageView* passwordBackground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gray"]];
        passwordBackground.frame = CGRectMake(15, 65, 248, 40);
        [self addSubview:passwordBackground];

        self.phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(25, 15, 228, 40)];
        self.phoneTextField.placeholder = @"手机号码";
        self.phoneTextField.delegate = self;
        self.phoneTextField.returnKeyType = UIReturnKeyDone;
        [self addSubview:self.phoneTextField];

        self.passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(25, 65, 228, 40)];
        self.passwordTextField.placeholder = @"设置密码";
        self.passwordTextField.delegate = self;
        [self.passwordTextField setSecureTextEntry:YES];
        self.passwordTextField.returnKeyType = UIReturnKeyDone;
        [self addSubview:self.passwordTextField];

        //获取验证码
        self.getCodeBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
        self.getCodeBtn.frame =CGRectMake(25, 125, 100, 38);
        self.getCodeBtn.adjustsImageWhenDisabled = YES;
        [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.getCodeBtn setBackgroundImage:[UIImage imageNamed:@"yellow1"] forState:UIControlStateNormal];
        [self.getCodeBtn setBackgroundImage:[UIImage imageNamed:@"yellow1_press"] forState:UIControlStateHighlighted];
        [self.getCodeBtn addTarget:self action:@selector(getCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.getCodeBtn];
        
        UIImageView * codeBackground = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"gray1"]];
        codeBackground.frame =CGRectMake(130, 125, 129, 40);
        [self addSubview:codeBackground];

        self.codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(140, 125, 110, 40)];
        self.codeTextField.placeholder = @"输入验证码";
        self.codeTextField.delegate = self;
        self.codeTextField.returnKeyType = UIReturnKeyDone;
        [self addSubview:self.codeTextField];

        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, 100, 38);
        button.center = CGPointMake(CGRectGetWidth(self.frame) / 2, 190);
        [button setTitle:@"注册" forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"yellow"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"yellow_press"] forState:UIControlStateHighlighted];

        [button addTarget:self action:@selector(registerClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];

        UIImageView* tipImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"words"]];

        tipImageView.frame = CGRectMake(0, 0, 168, 20);
        tipImageView.center = CGPointMake(CGRectGetWidth(self.frame) / 2, 225);

        [self addSubview:tipImageView];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    }
    return self;
}
-(void)setOriginRect:(CGRect)originRect{
    _originRect = originRect;
    self.frame = originRect;
}

- (void)getCodeBtnClick:(UIButton *)button {
    
        if ([self isValidateMobile:self.phoneTextField.text]) {
            VerificationCodeRequestData *request = [[VerificationCodeRequestData alloc] init];
            request.phone = self.phoneTextField.text;
            
            VerificationCodeResponseData *response = [[VerificationCodeResponseData alloc] init];
            [RequestFactory requestWithRequestData:request forResponseData:response complete:^(ResponseData *responseData, NSError *error) {
                if (responseData) {
                    VerificationCodeResponseData *response = (VerificationCodeResponseData *)responseData;
                    if (response.result == 1) {
                        [self startTimer];
                        [SVProgressHUD showSuccessWithStatus:@"验证码发送成功！"];
                    }else {
                        [SVProgressHUD showErrorWithStatus:response.info];
                    }
                }else{
                    NSLog(@"error %@",error.localizedDescription);
                }
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:@"请输入格式正确的手机号！"];
        }
}
- (void)startTimer {
    self.timerCount = 60;
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
    [self disableCodeButton];
}
- (void)stopTimer:(NSTimer *)timer
{
    [timer invalidate];
    self.timerCount = 0;
    [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self enableCodeButton];
}
- (void)disableCodeButton {
    [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.getCodeBtn.enabled = NO;
    self.getCodeBtn.userInteractionEnabled = NO;
}

- (void)enableCodeButton
{
    [self.getCodeBtn setTitle:@"重新获取(60)" forState:UIControlStateNormal];
    self.getCodeBtn.userInteractionEnabled = YES;
    self.getCodeBtn.enabled = YES;
}

- (void)onTimer:(NSTimer *)timer
{
    self.timerCount--;
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"重新获取(%ld)", (unsigned long)self.timerCount] forState:UIControlStateNormal];
    if (self.timerCount <= 0) {
        [self stopTimer:timer];
    }
}
-(void)registerClick:(UIButton *)button{
    if (self.phoneTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        return;
    }
    else if (self.passwordTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    else if ([self.codeTextField.text length] == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    
    NSParameterAssert(self.phoneTextField.text.length>0);
    NSParameterAssert(self.passwordTextField.text.length>0);
    NSParameterAssert(self.codeTextField.text.length>0);
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(registerClick:phone:password:code:)]){
        [self.delegate registerClick:button phone:self.phoneTextField.text password:self.passwordTextField.text code:self.codeTextField.text];
    }
}

/**
 *   手机号码验证
 *  @param mobile
 */
- (BOOL)isValidateMobile:(NSString*)mobile
{
    //手机号以13， 15，18开头，八个 \d 数字字符
    NSString* phoneRegex = @"^[1][3578]\\d{9}$";
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter ]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

-(void)keyboardShow:(NSNotification *)notification{
    self.frame = CGRectMake(21, CGRectGetMinY(self.originRect) - 200, 278, 188);
}

-(void)keyboardHide:(NSNotification *)notification{
    self.frame = self.originRect;
}

-(void)keyboardChange:(NSNotification *)notification{
    
}

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
}

- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(void)codeClick:(UIButton *)button{
    
}
@end
